package cn.tedu.disorder;

import java.util.Formatter;

public class Disorder {
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            Thread one = new Thread(() -> {
                // 由于线程one先启动，下面这句话让它等，等线程two，读者可以根据自己电脑的实际性能调整等待时间
                //shortWait(100000);
                a = 1;
                x = b;
            });

            Thread other = new Thread(() -> {
                b = 1;
                y = a;
            });

            one.start();
            other.start();
            one.join();
            other.join();

            // 这个程序涉及到指令重排
            // 第一个线程的 a = 1; x = b; 不一定谁先执行
            // 同理，第二个线程的 b = 1; y = a; 也不一定谁先执行

            Formatter formatter = new Formatter();
            formatter.format("第%d次(%d, %d)", i, x, y);
            if (x == 0 && y == 0) {
                System.out.println(formatter.toString());
                break;
            } else {
                //System.out.println(formatter.toString());
            }
        }
    }
}
